//
//  BookImp.swift
//  CoreDataSwift
//
//  Created by liuxiang on 2018/1/10.
//  Copyright © 2018年 liuxiang. All rights reserved.
//

import UIKit
import CoreData


class BookImp: NSObject, CoreDataBaseProtocol {
    
    
    
    var moc: NSManagedObjectContext
    
    init(context: NSManagedObjectContext) {
        self.moc = context
    }
    
    
    func excuteQuery(predicateString: String?, limitCount: Int, sortkeys: [String]?, ascending: Bool) -> [NSManagedObject]? {
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
        let entityDesc = NSEntityDescription.entity(forEntityName: "BcBook", in: self.moc)
        fetchRequest.entity = entityDesc
        fetchRequest.fetchLimit = limitCount
        if predicateString != nil {
            if !(predicateString!.isEmpty) {
                let predicate = NSPredicate(format: predicateString!, argumentArray: nil)
                fetchRequest.predicate = predicate
            }
        }
        
        if sortkeys != nil {
            var sortDescs = [NSSortDescriptor]()
            for (key) in sortkeys! {
                let sortDescriptor = NSSortDescriptor(key: key, ascending: ascending)
                sortDescs.append(sortDescriptor)
            }
            fetchRequest.sortDescriptors = sortDescs
        }
        
        do {
            let result = try self.moc.fetch(fetchRequest)
            return result as? [NSManagedObject]
        } catch {
            return nil
        }
    }
    
    func excuteDelete(predicateString: String?) -> Bool {
        guard let queryResult = excuteQuery(predicateString: predicateString, limitCount: 0, sortkeys: nil, ascending: true) else {
            // 没有查找到，返回成功
            return true
        }
        for managerObject in queryResult {
            self.moc.delete(managerObject)
        }
        return saveContext()
    }
    
    func excuteInsert(datasource: AnyObject) -> Bool {
        
        return saveContext()
    }
    
    private func saveContext () -> Bool {
        if self.moc.hasChanges {
            do {
                try self.moc.save()
                return true
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                print("Unresolved error \(nserror), \(nserror.userInfo)")
                return false
            }
        }
        return true
    }
}
